package com.app.zenmewan.controller;

import com.app.zenmewan.commons.Act;
import com.app.zenmewan.commons.Actions;
import com.app.zenmewan.commons.Message;
import com.app.zenmewan.entity.*;
import com.app.zenmewan.service.*;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * (Article)表控制层
 * 用于处理攻略文章
 *
 * @author makejava
 * @since 2020-05-02 20:03:18
 */
@RestController
@RequestMapping("article")
public class ArticleController {
    /**
     * 服务对象
     */
    @Resource
    private ArticleService articleService;
    @Resource
    private UserStatsticService userStatsticService;
    @Resource
    private UserService userService;
    @Resource
    private CommentService commentService;

    @Autowired
    private Actions actions;
    @Autowired
    private Act act;
    private static final Logger log = LoggerFactory.getLogger(ArticleController.class);

    @Setter
    @Getter
    class Vo {
        Article article;
        User user;
        String date;
    }

    private Vo getVo(Article article) {
        Vo v = new Vo();
        User u = this.userService.queryById(article.getUid());

        u.setPassword(null);
        u.setToken(null);
        int level = (int) Math.floor(Math.log(u.getPoint()) * 1.02);
        u.setLevel(level);
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd HH:mm");
        v.setDate(sdf.format(article.getCreatedate()));
        v.setUser(u);
        v.setArticle(article);
        return v;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Vo selectOne(Integer id) {
        Article a = this.articleService.queryById(id);
        a.setSeetimes(a.getSeetimes() + 1);
        this.articleService.update(a);
        return getVo(a);
    }

    @GetMapping("newtotal")
    public int newtotal() {
        return this.articleService.queryAll(new Article()).size();
    }

    @GetMapping("list/new")
    public ModelAndView newlist(int start) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        List<Article> l = this.articleService.queryAllByLimit(start, 10);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("typelist")
    public ModelAndView typelist(String name) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        Article a = new Article();
        a.setTypeName(name);
        List<Article> l = this.articleService.queryAll(a);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("userlist")
    public ModelAndView userlist(int uid) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        Article a = new Article();
        a.setUid(uid);
        List<Article> l = this.articleService.queryAll(a);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("shoucanglist")
    public ModelAndView shoucanglist(int uid) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        List<UserStatstic> l = this.userStatsticService.queryAll(us);
        List<Vo> vlist = new ArrayList<>();
        List<Article> al = new ArrayList<>();
        for (UserStatstic userStatstic : l) {
            if (userStatstic.getShoucang() == 1)
                al.add(this.articleService.queryById(userStatstic.getAid()));
        }
        for (Article article : al) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("dianzanlist")
    public ModelAndView dianzanlist(int uid) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        List<UserStatstic> l = this.userStatsticService.queryAll(us);
        List<Vo> vlist = new ArrayList<>();
        List<Article> al = new ArrayList<>();
        for (UserStatstic userStatstic : l) {
            if (userStatstic.getDianzan() == 1)
                al.add(this.articleService.queryById(userStatstic.getAid()));
        }
        for (Article article : al) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }
    @GetMapping("quxdianzan")
    public void quxdianzan(int uid,int aid){
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        us.setAid(aid);
        for (UserStatstic userStatstic : this.userStatsticService.queryAll(us)) {
            userStatstic.setDianzan(0);
            this.userStatsticService.update(userStatstic);
        }
    }
    @GetMapping("quxshoucang")
    public void quxshoucang(int uid,int aid){
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        us.setAid(aid);
        for (UserStatstic userStatstic : this.userStatsticService.queryAll(us)) {
            userStatstic.setShoucang(0);
            this.userStatsticService.update(userStatstic);
        }
    }
    @GetMapping("spot_article")
    public ModelAndView spot_article(int sid) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        Article a = new Article();
        a.setSid(sid);
        List<Article> l = this.articleService.queryAll(a);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("search")
    public ModelAndView search(String name) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        Article a = new Article();
        a.setTitle(name);
        a.setContent(name);
        List<Article> l = this.articleService.search(a);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("list/hot")
    public ModelAndView hotlist(int start) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        List<Article> l = this.articleService.queryAllHotByLimit(start, 10);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @GetMapping("list/tuijian")
    public ModelAndView tuijianlist(int start, String user_token) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        int user_id = 1;
        if (null == user_token || "".equals(user_token)) {
        } else {
            user_id = actions.checkUid(user_token);
        }
        List<Article> l = this.act.getList(user_id, start, 10);
        List<Vo> vlist = new ArrayList<>();
        for (Article article : l) {
            Vo v = getVo(article);
            vlist.add(v);
        }
        modelAndView.addObject("list", vlist);
        return modelAndView;
    }

    @PostMapping("save/{token}")
    public ModelAndView save(@PathVariable("token") String token, @RequestBody Article a) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        int result = actions.checkToken(token, modelAndView);
        //token 非法
        if (result == -1) {
            return modelAndView;
        } else {
            try {
                a.setUid(result);
                this.userService.Jiajifen(result,30);//加积分
                a.setSeetimes(0);
                a.setGoodtimes(0);
                a.setStartimes(0);
                a.setPingluntimes(0);
                this.articleService.insert(a);
                return modelAndView;
            } catch (Exception e) {
                modelAndView.setStatus(HttpStatus.BAD_REQUEST);
                modelAndView.addObject(Message.MESS, "意外出错:" + e.getLocalizedMessage());
                return modelAndView;
            }
        }
    }

    @PostMapping("update/{id}")
    public ModelAndView update(@PathVariable("id") String id, @RequestBody Article a) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        try {
            this.articleService.update(a);
            return modelAndView;
        } catch (Exception e) {
            modelAndView.setStatus(HttpStatus.BAD_REQUEST);
            modelAndView.addObject(Message.MESS, "意外出错:" + e.getLocalizedMessage());
            return modelAndView;
        }


    }

    //提交点赞
    @GetMapping("dianzan")
    public void dianzan(int artId, String token) {
        //获取userid
        int uid = this.actions.checkUid(token);
        //处理用户对文章的点赞
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        us.setAid(artId);
        List<UserStatstic> l = this.userStatsticService.queryAll(us);
        if (l.size() > 0) {
            UserStatstic f = l.get(0);
            ;
            f.setDianzan(1);
            this.userStatsticService.update(f);
        } else {
            UserStatstic n = new UserStatstic();
            n.setAid(artId);
            n.setUid(uid);
            n.setDianzan(1);
            n.setShoucang(0);
            this.userStatsticService.insert(n);
            //增加点赞次数
            Article article = this.articleService.queryById(artId);
            article.setGoodtimes(article.getGoodtimes() + 1);
            this.articleService.update(article);
        }
    }

    @GetMapping("quxiaodianzan")
    public void quxiaodianzan(int artId, String token) {
        //减少点赞次数
        Article article = this.articleService.queryById(artId);
        article.setGoodtimes(article.getGoodtimes() - 1);
        this.articleService.update(article);
        //获取userid
        int uid = this.actions.checkUid(token);
        //处理用户对文章的取消点赞
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        us.setAid(artId);
        //因为已经点赞过，所以不用查询是否存在
        UserStatstic f = this.userStatsticService.queryAll(us).get(0);
        f.setDianzan(0);
        this.userStatsticService.update(f);
    }

    //提交点赞
    @GetMapping("shoucang")
    public void shoucang(int artId, String token) {
        //增加收藏次数
        Article article = this.articleService.queryById(artId);
        article.setStartimes(article.getStartimes() + 1);
        this.articleService.update(article);
        //获取userid
        int uid = this.actions.checkUid(token);
        //处理用户对文章的收藏
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        us.setAid(artId);
        List<UserStatstic> l = this.userStatsticService.queryAll(us);
        if (l.size() > 0) {
            UserStatstic f = l.get(0);
            ;
            f.setShoucang(1);
            this.userStatsticService.update(f);
        } else {
            UserStatstic n = new UserStatstic();
            n.setAid(artId);
            n.setUid(uid);
            n.setShoucang(1);
            n.setDianzan(0);
            this.userStatsticService.insert(n);

        }
    }

    @GetMapping("quxiaoshoucang")
    public void quxiaoshoucang(int artId, String token) {
        //减少收藏次数
        Article article = this.articleService.queryById(artId);
        article.setStartimes(article.getStartimes() - 1);
        this.articleService.update(article);
        //获取userid
        int uid = this.actions.checkUid(token);
        //处理用户对文章的取消点赞
        UserStatstic us = new UserStatstic();
        us.setUid(uid);
        us.setAid(artId);
        //因为已经点赞过，所以不用查询是否存在
        UserStatstic f = this.userStatsticService.queryAll(us).get(0);
        f.setShoucang(0);
        this.userStatsticService.update(f);
    }

    //查看是否收藏和点赞过
    @GetMapping("look")
    public ModelAndView look(int artId, String token) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        UserStatstic us = new UserStatstic();
        us.setUid(this.actions.checkUid(token));
        us.setAid(artId);
        List<UserStatstic> l = this.userStatsticService.queryAll(us);
        if (l == null || l.size() == 0) {
            return modelAndView;
        } else {
            modelAndView.addObject("em", l.get(0));
            return modelAndView;
        }
    }

    @GetMapping("delete/{aid}")
    public void delete(@PathVariable("aid") int aid) {
        this.articleService.deleteById(aid);
        //删除评论
        Comment c = new Comment();
        c.setArtId(aid);
        for (Comment comment : this.commentService.queryAll(c)) {
            this.commentService.deleteById(comment.getId());
        }
        //删除统计内容
        UserStatstic us = new UserStatstic();
        us.setAid(aid);
        for (UserStatstic userStatstic : this.userStatsticService.queryAll(us)) {
            this.userStatsticService.deleteById(userStatstic.getId());
        }
    }

}